package kuba.common;

import java.util.Set;

import javax.swing.JOptionPane;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import kuba.bean.Author;
import kuba.bean.CD;

public class BeanValidator {

    private Validator validator;

    public BeanValidator() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator=factory.getValidator();
    }

    public boolean validateAuthor(Author author) {
        Set <ConstraintViolation<Author>> constraintViolations = validator.validate(author);
        if( !constraintViolations.isEmpty() ) {
            ConstraintViolation<Author> violation =constraintViolations.iterator().next();

            StringBuilder buffer = new StringBuilder();
            buffer.append(violation.getPropertyPath()).append(" ").append(violation.getMessage());
            
            JOptionPane.showMessageDialog(null,buffer.toString());
            return false;
        }
        return true;

    }

    public boolean validateCd (CD cd) {
        Set <ConstraintViolation<CD>> constraintViolations = validator.validate(cd);
        if( !constraintViolations.isEmpty() ) {
            ConstraintViolation<CD> violation =constraintViolations.iterator().next();

            StringBuilder buffer = new StringBuilder();
            buffer.append(violation.getPropertyPath()).append(" ").append(violation.getMessage());
            
            JOptionPane.showMessageDialog(null,buffer.toString());
            return false;
        }
        return true;
    }
}
